package xyz.lwm.lazycat.transaction.policy;

import xyz.lwm.lazycat.transaction.execute.TranDefinition;
import xyz.lwm.lazycat.transaction.execute.Transaction;
import xyz.lwm.lazycat.transaction.execute.TransactionException;
import xyz.lwm.lazycat.transaction.execute.TransactionManager;

/**
 * 若存在当前事务，则加入当前事务，若不存在当前事务，则抛出异常
 *
 * @author lwm
 * @see xyz.lwm.lazycat.transaction.execute.Propagation#MANDATORY
 */
class MandatoryPolicy extends AbstractPolicy {

    public MandatoryPolicy(TranDefinition tranDefinition) {
        super(tranDefinition);
    }

    @Override
    public <T> T execute(CheckedSupplier<T> supplier) throws Throwable {
        // 当前事务必须开启 (open)
        Transaction tran = TransactionManager.current();
        if (!tran.isOpen()) {
            throw new TransactionException("No transaction found");
        }
        return supplier.get();
    }

}
